#!/usr/bin/python

from utils import _exec_shell1

INTELCAS_CONF_FILE="/root/intelcas_uuid.conf"
CACHE_SECTION="[caches]"
CORE_SECTION="[cores]"
DEV_PREFIX="/dev/disk/by-uuid/"

def get_dev_by_uuid(uuid):
	cmd = "blkid -U %s" % (uuid)
	out, err = _exec_shell1(cmd, p=False)
	return out.strip()

def read_cache_section(intelcas_manage):
	list_cache = []
	with open(INTELCAS_CONF_FILE, 'r') as conf:
		for line in conf.readlines():
			real_line = line.strip()
			if DEV_PREFIX in real_line:
				list_cache = real_line.split(' ')
				cache_id = list_cache[0]
				cache_uuid = list_cache[1].split('/')[4]
				cache_dev = get_dev_by_uuid(cache_uuid)
				cache_mode = list_cache[3]
				if not intelcas_manage.is_running_cachedev(cache_dev):
					print 'running cachedev'
				else:
					print 'not running cachedev'

				"""
                if not intelcas_manage.is_running_cachedev(cache_dev):
                    cmd = "casadm --start-cache --cache-id %s --cache-device %s --cache-mode %s --force" % (cache_id, cache_dev, cache_mode)
                    print 'cmd:', cmd
                    _exec_shell1(cmd, p=False)
                else:
                    print '%s is already running!' % (cache_dev)
                """
			if real_line == CORE_SECTION:
				break

def read_core_section(intelcas_manage):
	list_core = []
	start = False
	with open(INTELCAS_CONF_FILE, 'r') as conf:
		for line in conf.readlines():
			real_line = line.strip()
			if real_line == CORE_SECTION:
				start = True
			if start:
				if DEV_PREFIX in real_line:
					list_core = real_line.split(' ')
					cache_id = list_core[0]
					core_uuid = list_core[1].split('/')[4]
					core_dev = get_dev_by_uuid(core_uuid)
					if not intelcas_manage.is_running_coredev(core_dev):
						cmd = "casadm --add-core --cache-id %s --core-device %s" % (cache_id, core_dev)
						print 'cmd:', cmd
						_exec_shell1(cmd, p=False)
					else:
						print '%s is already running!' % (core_dev)


if __name__ == '__main__':
	from node import Node
	node = Node()
	read_cache_section(node.disk_manage.intelcas_manage)
	#read_core_section()
